package com.xiaozhen.jt809.utils;

import java.nio.charset.Charset;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * HISTORY
 *
 * @author zhenweisheng
 * @date 2021/9/18 9:46
 * @description:
 */
public class DateUtil {

    /**
     * "[11]日": 17,
     * "[09]月": 9,
     * "[07E5]年": 2021,
     * "[10]时": 16,
     * "[21]分": 33,
     * "[17]秒": 23,
     *
     * @param dateTime
     * @return
     */
    public static String parseDateTime(byte[] dateTime) {
        int year = ByteArrayUtil.bytes2int(ByteArrayUtil.subBytes(dateTime, 2, 2));
        int month = ByteArrayUtil.bytes2int(ByteArrayUtil.subBytes(dateTime, 1, 1));
        int day = ByteArrayUtil.bytes2int(ByteArrayUtil.subBytes(dateTime, 0, 1));
        int hour = ByteArrayUtil.bytes2int(ByteArrayUtil.subBytes(dateTime, 4, 1));
        int minute = ByteArrayUtil.bytes2int(ByteArrayUtil.subBytes(dateTime, 5, 1));
        int second = ByteArrayUtil.bytes2int(ByteArrayUtil.subBytes(dateTime, 6, 1));
        return "" + year +
                (month < 10 ? "0" + month : month) +
                (day < 10 ? "0" + day : day) +
                (hour < 10 ? "0" + hour : hour) +
                (minute < 10 ? "0" + minute : minute) +
                (second < 10 ? "0" + second : second);
    }

    /**
     * 将时间戳转换为时间  单位：秒
     *
     * @param stamp
     * @return
     * @throws Exception
     */
    public static String stampToTime(int stamp) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        long stampLong = stamp * 1000L;
        Date date = new Date(stampLong);
        String res = simpleDateFormat.format(date);
        return res;
    }

    public static Date parse2Date(String dateString, String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        Date date = null;
        try {
            date = sdf.parse(dateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    public static Long parseMicTime(String dateString) {
        Date date = parse2Date(dateString, "yyyyMMddHHmmss");
        if (date == null) {
            return 0L;
        }
        // 微秒
        Long cuTime = date.getTime() * 1000;
        // 纳秒
        Long nanoTime = System.nanoTime();
        return cuTime + (nanoTime - nanoTime / 1000000 * 1000000) / 1000;
    }
}
